﻿using ShiQuan.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShiQuan.AppUpdateBLL
{
    /// <summary>
    /// 程序轮询业务处理
    /// </summary>
    public class AppTimerBLL : IDisposable
    {
        private System.Timers.Timer sysTimer = null;
        private System.ComponentModel.BackgroundWorker bgWorker = null;
        private bool _RunState = false;
        private DateTime _RunTime = DateTime.Now;

        private AppUpdaterBLL appUpdaterBLL = null;
        /// <summary>
        /// 开始轮询
        /// </summary>
        /// <returns></returns>
        public bool Start(int interval = 60)
        {
            try
            {
                if (_RunState)
                    return true;
                this._RunState = true;
                if (interval < 10)
                    interval = 10;
                //后台任务
                this.RunWorker();
                //计时器
                this.sysTimer = new System.Timers.Timer();
                this.sysTimer.Interval = interval * 1000;
                this.sysTimer.Elapsed += SysTimer_Elapsed;
                this.sysTimer.Start();
                return true;
            }
            catch (Exception ex)
            {
                this._RunState = false;
                Logger.Error("启动轮询业务异常：" + ex.ToString());
                return false;
            }
        }
        private void SysTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (this.bgWorker != null && this.bgWorker.IsBusy)
            {
                Logger.Info("后台任务正在执行...");
                TimeSpan timeSpan = DateTime.Now - this._RunTime;
                if (timeSpan.TotalMinutes <= 30)
                    return;
                Logger.Info("后台任务超："+timeSpan.TotalMinutes+" 未结束，取消任务...");
                this.bgWorker.CancelAsync();
                this.bgWorker = null;
                return;
            }
            this.RunWorker();
        }

        private void RunWorker()
        {
            //后台线程
            this.bgWorker = new System.ComponentModel.BackgroundWorker();
            this.bgWorker.WorkerReportsProgress = true;
            this.bgWorker.WorkerSupportsCancellation = true;
            this.bgWorker.DoWork += BgWorker_DoWork;
            this.bgWorker.ProgressChanged += BgWorker_ProgressChanged;
            this.bgWorker.RunWorkerCompleted += BgWorker_RunWorkerCompleted;
            this.bgWorker.RunWorkerAsync();
        }
        private void BgWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                this._RunTime = DateTime.Now;
                this.appUpdaterBLL = new AppUpdaterBLL();

                this.appUpdaterBLL.CheckUpdate(AppSetting.AppPath);
            }
            catch (Exception)
            {

                throw;
            }
            
        }
        private void BgWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            
        }

        private void BgWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            
        }

        
        /// <summary>
        /// 停止轮询
        /// </summary>
        public void Stop()
        {
            this._RunState = false;
            if(this.sysTimer != null)
            {
                this.sysTimer.Stop();
                this.sysTimer.Dispose();
                this.sysTimer = null;
            }
            if(this.bgWorker != null)
            {
                this.bgWorker.CancelAsync();
                this.bgWorker.Dispose();
                this.bgWorker = null;
            }
        }
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            this.Stop();
        }
    }
}
